package com.ruoyi.socket.probuffer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializationUtils {
    /**
     *  序列化
     *
     * @param obj
     * @return
     */
    public static byte[] serialize(Object obj)  {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try{
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);
            oos.flush();
            oos.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return baos.toByteArray();
    }
    /**
     *  反序列化
     *
     * @param bytes
     * @return
     */
    public static Object deserialize(byte[] bytes){
        try{
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            Object obj = ois.readObject();
            ois.close();
            return obj;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
